﻿using AspectCore.Configuration;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using System;
using NetMicro.Core.ConfigureOptions;
using NetMicro.Core.Ioc;
using NetMicro.HttpClient.AspectExtend;
using NetMicro.HttpClient.Proxies;
using NetMicro.Nacos;

namespace NetMicro.Host
{
    /// <summary>
    /// WebHost构造器
    /// </summary>
    public class HostBuilder
    {
        /// <summary>
        /// 启动
        /// </summary>
        /// <typeparam name="TStartup"></typeparam>
        /// <param name="args">启动参数</param>
        public void Run<TStartup>(string[] args) where TStartup : StartupProvider
        {
            CreateBuilder<TStartup>(args).Build().Run();
        }

        /// <summary>
        /// 创建主机生成器
        /// </summary>
        /// <typeparam name="TStartup"></typeparam>
        /// <param name="args"></param>
        /// <returns></returns>
        public IHostBuilder CreateBuilder<TStartup>(string[] args) where TStartup : StartupProvider
        {

            return Microsoft.Extensions.Hosting.Host.CreateDefaultBuilder(args)
                    .UseConfigHostBuilder()
                    .UseDependencyProvider(config =>
                    {
                        config.Interceptors.AddTyped<HttpServiceBusProxy>(Predicates.Implement(typeof(IHttpServiceBusProxy)));
                        config.Interceptors.AddTyped<HttpProxy>(Predicates.Implement(typeof(IHttpProxy)));

                    })
                    .ConfigureWebHostDefaults(webBuilder =>
                    {
                        webBuilder.ConfigureKestrel((context, options) =>
                        {
                            //设置应用服务器Kestrel请求体最大为50MB,//52428800
                            options.Limits.MaxRequestBodySize = int.MaxValue;
                            //api请求超时
                            options.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(20);
                            options.Limits.RequestHeadersTimeout = TimeSpan.FromMinutes(20);
                        });
                        webBuilder
                            .UseStartup<TStartup>();
                    });
        }
    }
}